import {
	getToken,
	setToken
} from '@/utils/auth'
import {
	OpenBridge,
	TopSys
} from "open-bridge";
import {
	getInfo
} from '@/api/login'
import {
	getCheckInfo
} from "@/api/login.js"
// 登录页面
const loginPage = "/pages/login"
//第三方跳转获得token
let isToken = ""

// 页面白名单
const whiteList = [
	'/pages/login', '/pages/register', '/pages/common/webview/index'
]

// 检查地址白名单 
function checkWhite(url) {
	const path = url.split('?')[0]
	return whiteList.indexOf(path) !== -1
}
// 回调形式
const handleClick = () => {
	OpenBridge.create().topSys.getOTP(({
		isSuccess,
		otp,
		error
	}) => {
		if (isSuccess) {
			console.log("otp===", otp);
			let ssCode = otp
			getCheckInfo(ssCode).then((res) => {
				isToken = res.token
				setToken(res.token)
				//跳转将信息存储到storage里面
				getInfo().then((res) => {
					// 用户信息,存储数据
					uni.setStorageSync('userInfo', res.user)
				})
				if (isToken != null && isToken != '') {
					uni.reLaunch({
						url: '/pages/index'
					})
				} else {
					uni.reLaunch({
						url: loginPage
					})
				}

				console.log("获取sscode", res)
			})
		} else {
			console.error(error);
		}
	});
}

handleClick()
// 页面跳转验证拦截器
let list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"]
list.forEach(item => {
	uni.addInterceptor(item, {
		invoke(to) {
			if (getToken()) {
				if (to.url === loginPage) {
					uni.reLaunch({
						url: "/"
					})
				}
				return true
			} else {
				if (checkWhite(to.url)) {
					return true
				}

				uni.reLaunch({
					url: loginPage
				})
				return false
			}
		},
		fail(err) {
			console.log(err)
		}
	})
})